package org.xxpay.pay.channel.xypay;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.MD5Util;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayNotify;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Service
public class XypayPayNotifyService extends BasePayNotify {

    private static final MyLog _log = MyLog.getLog(XypayPayNotifyService.class);
    private static final String logPrefix = "【处理"+ XypayConfig.CHANNEL_NAME+"支付回调】";

    @Override
    public String getChannelName() {
        return XypayConfig.CHANNEL_NAME;
    }

    @Override
    public JSONObject doNotify(Object notifyData) {
        _log.info("====== 开始处理{}支付回调通知 ======", getChannelName());
        HttpServletRequest request = (HttpServletRequest) notifyData;
        JSONObject retObj = buildRetObj();
        Map<String, String> payContext = new HashMap();

        String respString = XypayConfig.RETURN_VALUE_ERROR;
        try {
            PayOrder payOrder = verifyPayParams(request, payContext);
            if( payOrder == null ) { //验证参数失败
                retObj.put(PayConstant.RESPONSE_RESULT, XypayConfig.RETURN_VALUE_ERROR);
                return retObj;
            }
            //订单已经支付完成
            if(payOrder.getStatus() == PayConstant.PAY_STATUS_SUCCESS || payOrder.getStatus() == PayConstant.PAY_STATUS_COMPLETE){
                retObj.put(PayConstant.RESPONSE_RESULT, XypayConfig.RETURN_VALUE_SUCCESS);
                return retObj;
            }

            int updatePayOrderRows = commonService.payOrderService.updateStatus4Success(payOrder.getPayOrderId());
            if (updatePayOrderRows != 1) {
                _log.error("{}更新支付状态失败,将payOrderId={},更新payStatus={}失败", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
                retObj.put(PayConstant.RESPONSE_RESULT, "处理订单失败");
                return retObj;
            }
            _log.error("{}更新支付状态成功,将payOrderId={},更新payStatus={}成功", logPrefix, payOrder.getPayOrderId(), PayConstant.PAY_STATUS_SUCCESS);
            payOrder.setStatus(PayConstant.PAY_STATUS_SUCCESS);

            // 业务系统后端通知
            baseNotify4MchPay.doNotify(payOrder, true);
            _log.info("====== 完成处理{}支付回调通知 ======", getChannelName());
            respString = XypayConfig.RETURN_VALUE_SUCCESS;
        } catch (Exception e) {
            _log.error(e, logPrefix + "处理异常");
        }
        retObj.put(PayConstant.RESPONSE_RESULT, respString);
        return retObj;
    }

    /**
     * 验证通知参数
     * @return
     */
    public PayOrder verifyPayParams(HttpServletRequest request, Map<String, String> payContext) {

        String orderid = request.getParameter("orderid");
        String money = request.getParameter("money");
        String sign = request.getParameter("sign");
        String status = request.getParameter("status");

        _log.info("{}通知参数=> orderid:{}, money={}, sign={}, status={}", logPrefix, orderid, money, sign, status);

        if(StringUtils.isBlank(orderid)) {
            return null;
        }
        if(!"0000".equals(status)) {
            return null;
        }

        // 查询payOrder记录
        String payOrderId = orderid;
        PayOrder payOrder = commonService.payOrderService.findByPayOrderId(payOrderId);
        if (payOrder == null) {
            _log.error("Can't found payOrder form db. payOrderId={}, ", payOrderId);
            return null;
        }

        XypayConfig xypayConfig = new XypayConfig(getPayParam(payOrder));
        String signValue = MD5Util.string2MD5("money="+money+"&orderid="+orderid+"&status="+status+"&key="+xypayConfig.getKey());
        if(!sign.equals(signValue)) {
            _log.error("验证签名失败. payOrderId={}, ", payOrderId);
            return null;
        }

        return payOrder;
    }

}
